<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        /* 
            往服务端上传文件步骤
                1.通过file类型的标签选择上传的文件
                2.获取标签元素对象，file类型标签中属性 files 里面存储了文件数组
                3.利用FormData将其打包上传到服务端去
                4.对服务端的响应进行处理
        */
    </script>
</head>
<body>
    <input type="file" id="file1"><br>
    <button>上传图片</button><br>
    <img src="" alt="" width="500px" height="600px">
    <script>
        const request = new XMLHttpRequest();
        const fileObj = document.querySelector("#file1");
        const btnObj = document.querySelector("button")
        const imgObj = document.querySelector("img");
        btnObj.addEventListener("click",function(){
            if(fileObj.files.length<=0){
                return alert("请选择文件");
            }
                const formData = new FormData();
                formData.append('files',fileObj.files[0]);
                request.open("POST","http://localhost:8080/Day06_response_request_war_exploded/reqUpload/demo01");
                request.send(formData);
                request.onreadystatechange = function(){
                    if(request.readyState == 4 && request.status == 200){
                        console.log(request.responseText);
                        const responseValue = JSON.parse(request.responseText);
                        if(responseValue.msg == "文件上传成功"){
                            imgObj.src = 'http://localhost:8080/Day06_response_request_war_exploded/reqUploads/' + responseValue.fileName;
                        }
                    }
            }
        })
    </script>
</body>
</html>